package cn.schoolwow.quickdao.module.database.ddl.kit;

import cn.schoolwow.quickdao.module.database.ddl.action.kit.DatabaseDefinitionActionImpl;
import cn.schoolwow.quickdao.module.database.ddl.query.kit.DatabaseDefinitionQueryImpl;
import cn.schoolwow.quickflow.QuickFlow;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 数据定义语言 - 代理对象
 */
public class DatabaseDefinitionInvocationHandler implements InvocationHandler {
    private Object[] interfaceInstanceArray;

    public DatabaseDefinitionInvocationHandler(QuickFlow quickFlow) {
        DatabaseDefinitionQueryImpl databaseDefinitionQuery = new DatabaseDefinitionQueryImpl(quickFlow);
        interfaceInstanceArray = new Object[]{
                databaseDefinitionQuery,
                new DatabaseDefinitionActionImpl(databaseDefinitionQuery, quickFlow)
        };
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String interfaceName = method.getDeclaringClass().getSimpleName();
        for(Object interfaceInstance:interfaceInstanceArray){
            Class interfaceClass = interfaceInstance.getClass().getInterfaces()[0];
            if(interfaceClass.getSimpleName().equalsIgnoreCase(interfaceName)){
                try {
                    return method.invoke(interfaceInstance, args);
                }catch (InvocationTargetException e){
                    Throwable targetException = e.getTargetException();
                    throw targetException;
                }
            }
        }
        throw new IllegalAccessError("不支持调用该方法!方法名:"+method.getName());
    }
}
